$(function() {
    var template = new Template(temp);
    template.Render("#designer");

    //默认禁用工具条
    disabledToolbar();

    // 标签渲染
    $(controls).each(function() {
        var nodeHtml = "";
        var that = this;

        function appendHtml() {
            if (nodeHtml.substr(nodeHtml.length - 5, 5) !== "</tr>") {
                nodeHtml += "<td></td></tr>";
            }
            $("#designer_controls").append(`
            <div class="panel panel-default">
                <div class="panel-heading" role="tab" id="heading${that.id}">
                    <h4 class="panel-title">
                        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#designer_controls" href="#collapse${that.id}" aria-expanded="true" aria-controls="collapse${that.id}">
                            ${that.name}
                        </a>
                    </h4>
                </div>
                <div id="collapse${that.id}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading${that.id}">
                    <div class="panel-body">
                        <table class="table table-bordered">
                            ${nodeHtml}
                        </table>
                    </div>
                </div>
            </div>`);
        }

        var nodes = $(this.nodes);
        if (nodes.length == 0) {
            appendHtml();
            return;
        }
        nodes.each(function(index) {
            nodeHtml += `
                ${index%2===0?"<tr>":""}
                <td>
                    <div class="origin_control"
                        id="origin_control${this.id}"
                        ctype="${this.type}"
                        cname="${this.name}"
                        filed="${this.filed}"
                        default="${this.default}">
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-${this.type}"></use>
                        </svg> ${this.name}
                    </div>
                </td>
                ${index%2===0?"":"</tr>"}`;
            if (index === nodes.length - 1) {
                appendHtml();
            }
        });

    });

    // 标签拖动
    $(".origin_control").each(function() {
        $(this).draggable({
            cursor: "move",
            cursorAt: {
                top: 10,
                left: 30
            },
            opacity: 0.7,
            helper: function(event) {
                return $(`<div class='origin_control_drag'>${$(this).html()}</div>`);
            }
        })
    });

    var designer = $("#designer");
    // 标签拖入
    designer.droppable({
        drop: function(event, ui) {
            var origin_control = $(ui.draggable);
            if (origin_control.hasClass("new_control")) return;
            var ctype = origin_control.attr("ctype");
            var cname = origin_control.attr("cname");
            var filed = origin_control.attr("filed");
            var defaultValue = origin_control.attr("default");
            if (isEmptyStr(defaultValue)) {
                defaultValue = cname;
            }
            var offset = designer.offset();
            var xPoint = event.pageX - offset.left - 13;
            var yPoint = event.pageY - offset.top - 11;
            var chtml = "";
            var num = getRandomNum();
            switch (ctype) {
                case "filed":
                    chtml = `
                    <div class="new_control_filed"
                        ctype="${ctype}"
                        cname="${ctype}"
                        filed="${filed}"
                        default="${defaultValue}">
                        ${defaultValue}
                    </div>`;
                    break;
                case "label":
                    chtml = `
                    <div class="new_control_label"
                        ctype="${ctype}"
                        cname="${ctype}"
                        filed="${filed}"
                        default="${defaultValue}">
                        ${defaultValue}
                    </div>`;
                    break;
                case "barcode":
                    chtml = `
                    <div class="new_control_label"
                        ctype="${ctype}"
                        cname="${ctype}"
                        filed="${filed}"
                        default="${defaultValue}">
                        <svg id="barcode_${num}"
                            jsbarcode-format="EAN13"
                            jsbarcode-value="123456789012"
                            jsbarcode-textmargin="0"
                            jsbarcode-fontoptions="bold"
                            jsbarcode-width="1px"
                            jsbarcode-height="50px">
                        </svg>
                    </div>`;
                    break;
                case "qrcode":
                    break;
                case "image":
                    break;
            }
            designer.append(`
            <div class="new_control" style="left:${xPoint}px;top:${yPoint}px;width:100px;height:24px;" id="control_${num}" tabindex="${num}">
                ${chtml}
            <div>`);
            if (ctype === "barcode") {
                JsBarcode(`#barcode_${num}`).init();
            }
            var newControl = $(`#control_${num}`);
            // 可拖动
            newControl.draggable({
                cursor: "move",
                containment: designer,
                scroll: false,
                start: function(event, ui) {

                },
                drag: function(event, ui) {

                },
                stop: function(event, ui) {

                }
            });
            // 可调整大小
            newControl.resizable({ minHeight: 24, minWidth: 40 });
            // 点击
            newControl.click(function() {
                newControl.focus();
                $(".new_control").removeClass("ui-selected");
                newControl.addClass("ui-selected");
                enabledToolbar();
                // 设置工具条样式
                setToolbar(newControl);
                // todo:显示控件相关信息
            });
            newControl.keydown(function(e) {
                if (e.which != 46) return;
                if (confirm("确认移出当前控件？")) {
                    newControl.remove();
                    disabledToolbar();
                }
            });
            newControl.trigger("click");
        }
    });

    // 设计器选择
    designer.selectable({
        filter: ".new_control",
        stop: function(event, ui) {
            var controls = $(".ui-selected.new_control");
            if (controls.length === 0) {
                disabledToolbar();
                return;
            }
            enabledToolbar();
            setToolbar(controls);
        }
    });

    // 字体大小选择
    $("#ddlFontSize li").click(function() {
        var fontSize = $(this).attr("datafield");
        $("#font_size").html(fontSize);
        $(".ui-selected.new_control").css("font-size", fontSize);
    });

    // 对齐方式选择
    $("#ddlFontAlign li").click(function() {
        var textAlign = $(this).attr("datafield");
        setTextAlign(textAlign);
        $(".ui-selected.new_control").css("text-align", textAlign);
    });

    // 字体选择
    $("#ddlFontFamily li").click(function() {
        var fontFamily = $(this).attr("datafield");
        $("#font_family").html(fontFamily);
        $(".ui-selected.new_control").css("font-family", fontFamily);
    });

    // 颜色选择
    $('#color_selected').colorpicker({
        strings: "主题颜色,标准颜色,网页颜色,主题颜色,返回调色板,历史记录,暂无历史记录"
    }).on('change.color', (evt, color) => {
        $('#btnSelectColor').css('color', color);
        $(".ui-selected.new_control").css('color', color);
    });

    $('#btnSelectColor').click((evt) => {
        $('#color_selected').next().trigger("click");
    });

    // 字体粗细
    $("#btnFontWeight").click(function() {
        var fontWeight = "400";
        if ($(this).hasClass("btn-primary")) {
            $(this).removeClass("btn-primary");
        } else {
            $(this).addClass("btn-primary");
            fontWeight = "700";
        }
        $(".ui-selected.new_control").css('font-weight', fontWeight);
    });

    // 字体正斜
    $("#btnFontItalic").click(function() {
        var fontStyle = "normal";
        if ($(this).hasClass("btn-primary")) {
            $(this).removeClass("btn-primary");
        } else {
            $(this).addClass("btn-primary");
            fontStyle = "italic";
        }
        $(".ui-selected.new_control").css('font-style', fontStyle);
    });

    // 字体下划线
    $("#btnTextDecoration").click(function() {
        var textDecoration = "none";
        if ($(this).hasClass("btn-primary")) {
            $(this).removeClass("btn-primary");
        } else {
            $(this).addClass("btn-primary");
            textDecoration = "underline";
        }
        $(".ui-selected.new_control").css('text-decoration', textDecoration);
    });

    // 删除控件
    $("#btnDelControl").click(function() {
        if (confirm("确定移除选中的控件？")) {
            $(".ui-selected.new_control").remove();
            disabledToolbar();
        }
    });

    // 背景选择
    $("#background_selected").change(function(event) {
        if (event.target.files.length === 0) return;
        var reader = new FileReader();
        reader.onload = function() {
            designer.css("background-image", `url("${this.result}")`);
        };
        reader.readAsDataURL(event.target.files[0]);
    });

    // 打开模板编辑模态框
    $("#btnTemplateEdit").click(function() {
        $("#TemplateEditModal").modal();
    });

    // 模态框加载
    $("#TemplateEditModal").on("show.bs.modal", function() {
        var modal = $(this);
        modal.find(".modal-body input").val("1");
    });
});